//
//  InfoUIM.m
//  mbstore
//
//  Created by huangyi on 14-3-12.
//  Copyright (c) 2014年 huangyi. All rights reserved.
//

#import "ProductInfo.h"
#import "StrikeThroughLabel.h"
#import "DefultCor.h"
#import "UIImageView+WebCache.h"
#import "SearchStock.h"
@interface ProductInfo ()

@property(nonatomic,weak)IBOutlet UIScrollView *itemScrollView;
@property(nonatomic,weak)IBOutlet UIImageView *itemImage;
@property(nonatomic,weak)IBOutlet UITextView *itemName;
@property(nonatomic,weak)IBOutlet UITextView *itemNumber;
@property(nonatomic,weak)IBOutlet UILabel *itemPrice;
@property(nonatomic,weak)IBOutlet UIScrollView *colorScrollView;
@property(nonatomic,weak)IBOutlet UIScrollView *sizeScrollView;
@property(nonatomic,weak)IBOutlet UILabel *itemStock;
@property(nonatomic,weak)IBOutlet UIButton *buyButton;
@property(nonatomic,weak)IBOutlet UIButton *closeButton;
@property (nonatomic,strong)NSMutableArray *mlIsShow;
@property (nonatomic,strong)NSMutableArray *mlRowNum;
@property(nonatomic,strong)NSMutableDictionary *sku;

@end

@implementation ProductInfo

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
#pragma mark 初始化商品库存查询server
        self.commoditiesc = [[CommoditiesController alloc] init];
        self.delegate=self;
        self.dataSource=self;
        self.separatorInset=UIEdgeInsetsMake(0, 0, 0, 0);
        self.separatorStyle=UITableViewCellSeparatorStyleNone;
        self.showsHorizontalScrollIndicator=NO;
        self.showsVerticalScrollIndicator=NO;
        self.backgroundColor=[UIColor clearColor];
        self.bounces=NO;
        [self.layer setBorderWidth:2];
        [self.layer setBorderColor:TABLEBOR.CGColor];
       
         mlDicStock=[NSMutableDictionary dictionary];
        [self reloadData];
        
    }
    return self;
}
-(void)GetStock:(NSString *)skuId{
    _servers=[SearchStock GetStocks:skuId];
    _servers.delegate = self;
}
-(void)receiveData:(NSDictionary *)dic WithPath:(NSString *)path
{
    
}
-(void)FailureData:(NSString *)path WithError:(NSError *)error{
    [mlDicStock setObject:@"22" forKey:path];
    [self reloadData];
    NSLog(@"%@",path);
}

//- (void)viewDidLoad
//{
//    [super viewDidLoad];
//    // Do any additional setup after loading the view from its nib.
//
//    self.sku=[NSMutableDictionary dictionary];
//
//    [self.closeButton setImage:[UIImage imageNamed:@"media.bundle/close.png"] forState:UIControlStateNormal];
//    [self.buyButton setBackgroundImage:[UIImage imageNamed:@"media.bundle/buy.png"] forState:UIControlStateNormal];
//    [self.buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//}

//- (void)didReceiveMemoryWarning
//{
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return self.mlRowNum.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
//    if (section==[self numberOfSections]-1) {
//        if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
//            return [[self.mlRowNum objectAtIndex:section] intValue];
//        }
//        return 0;
//    }
//    else {
//        if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
//            return [[self.mlRowNum objectAtIndex:section] intValue];
//        }
//        return 1;
//    }
    if ([[self.mlIsShow objectAtIndex:section]boolValue])
        return [[self.mlRowNum objectAtIndex:section] intValue];
    else {
        if (section==[self numberOfSections]-1)return 0;
        
    }
    return 1;
    //    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier=@"pdt";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.clipsToBounds=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
    }
    else{
        while ([cell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
        
    }
    cell.backgroundColor=[UIColor whiteColor];
    if (indexPath.section!=[self numberOfSections]-1) {
         NSDictionary *goods=[_items[@"goods"] objectAtIndex:indexPath.section];
        if (indexPath.row==0) {
            [self ProductDetail:cell Meg:goods Index:indexPath];
            cell.backgroundColor=GRYCOLOR;
        }
        else{
            cell.backgroundColor=GRYCOLOR;
            NSArray *colors=[goods objectForKey:@"colors"];
            NSArray *size=[[colors objectAtIndex:0] objectForKey:@"sizes"];
            [self SizeProduct:cell Meg:size Index:indexPath];
        }
    }
    else {
        if (indexPath.row==0) {
            
            UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 15, CGRectGetWidth(self.frame)-20, CGRectGetHeight([self rectForRowAtIndexPath:indexPath])-30)];
            lab.text=[_items objectForKey:@"salePoint"];
            lab.numberOfLines=0;
            lab.font=[UIFont systemFontOfSize:15];
            [cell.contentView addSubview:lab];
        }
        
    }

    
    
//    if (indexPath.section==0) {
//        //        基本信息
//        [self ProductDetail:cell Meg:[_items[@"goods"] objectAtIndex:0]];
//        cell.backgroundColor=GRYCOLOR;
//        //        颜色图片
//    }
//    else if(indexPath.section==1){
//        cell.backgroundColor=GRYCOLOR;
//        [self SizeProduct:cell Meg:nil Index:indexPath];
//    }
//    
//    else if(indexPath.section==2){
//        [self ProductDetail:cell Meg:[_items[@"goods"] objectAtIndex:1]];
//        UIView *labLine=[[UIView alloc]initWithFrame:CGRectMake(10, CGRectGetHeight([self rectForRowAtIndexPath:indexPath])-5, CGRectGetWidth([self rectForRowAtIndexPath:indexPath])-20, 0.5)];
//        labLine.backgroundColor=LINECOR;
//        [cell.contentView addSubview:labLine];
//    }
//    else if(indexPath.section==3){
//        if (indexPath.row==0) {
//            
//            UILabel *lab=[[UILabel alloc]initWithFrame:CGRectMake(10, 15, CGRectGetWidth(self.frame)-20, CGRectGetHeight([self rectForRowAtIndexPath:indexPath])-30)];
//            lab.text=[_items objectForKey:@"salePoint"];
//            lab.numberOfLines=0;
//            lab.font=[UIFont systemFontOfSize:15];
//            [cell.contentView addSubview:lab];
//        }
//        
//    }
    //    cell.textLabel.text=@"fslkahgl";
    return cell;
}
//单品详情
-(void)ProductDetail:(UITableViewCell *)cell Meg:(NSDictionary *)dicInfo  Index:(NSIndexPath *)indexPath{
    UIImageView *imgProduct=[[UIImageView alloc]initWithFrame:CGRectMake(10, 15, 60, 60)];
    [imgProduct.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [imgProduct.layer setBorderWidth:1];
    [imgProduct setImageWithURL:[NSURL URLWithString:dicInfo[@"mainPhoto"]]];
    [cell.contentView addSubview:imgProduct];
    UILabel *labName=[[UILabel alloc]initWithFrame:CGRectMake(75, 13, 180, 20)];
    labName.numberOfLines=0;
    labName.font=[UIFont systemFontOfSize:14];
    [cell.contentView addSubview:labName];
    
    UILabel *labNum=[[UILabel alloc]initWithFrame:CGRectMake(75,CGRectGetMaxY(labName.frame) +2, 180, 20)];
    labNum.font=[UIFont systemFontOfSize:14];
    [cell.contentView addSubview:labNum];
    
    UILabel *labMoney=[[UILabel alloc]initWithFrame:CGRectMake(75, CGRectGetMaxY(labNum.frame)+2, 60, 20)];
    
    StrikeThroughLabel *strikeLab=[[StrikeThroughLabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(labMoney.frame)+5, CGRectGetMaxY(labNum.frame)+2, 60, 20)];
    labName.text=[NSString stringWithFormat:@"%@:%@",dicInfo[@"category"],dicInfo[@"goodsName"]];
    labNum.text=[NSString stringWithFormat:@"编号:%@",dicInfo[@"colorSn"]];
//    labMoney.text=@"￥67";
#pragma mark 添加price
#warning 套装事报错
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"" forKey:kUserID];
    [self.commoditiesc ScanBarCodeIntoBillEntity:dicInfo[@"colorSn"] Qty:@"1" ContainerID:@"" IsJudgePrice:@"true" StartNum:1 EndNum:1 Success:^(NSDictionary *dicReceiveData) {
        
        NSMutableArray * entityArray = [dicReceiveData objectForKey:@"Message"];
        EPOSDetailEntity * entity = [entityArray objectAtIndex:0];
        NSLog(@"+%@",entity.SalesValue);
        //                    [suit setValue:entity.SalesValue forKey:@"price"];
        labMoney.text=[NSString stringWithFormat:@"¥%@",entity.SalesValue];
        
    } Failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"查询价格出错！"];
    }];

    strikeLab.strikeThroughEnabled=YES;
    strikeLab.text=[NSString stringWithFormat:@"%@",dicInfo[@"marketPrice"]];
    strikeLab.textColor=[UIColor lightGrayColor];
    labMoney.textColor=[UIColor redColor];
    [cell.contentView addSubview:labMoney];
    [cell.contentView addSubview:strikeLab];
    
    UIButton *btnSelect;
    btnSelect=[[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width-40, CGRectGetMaxY(labNum.frame)-5, 30, 30)];
    btnSelect.tag=10001+indexPath.section;
    if ([[self.mlIsShow objectAtIndex:indexPath.section]boolValue]) {
        [btnSelect setImage:[UIImage imageNamed:@"colorDown"] forState:UIControlStateNormal];
    }
    else{
        [btnSelect setImage:[UIImage imageNamed:@"colorUp"] forState:UIControlStateNormal];
    }
    
    [btnSelect addTarget:self action:@selector(HideRow:) forControlEvents:UIControlEventTouchUpInside];
   
    [cell.contentView addSubview:btnSelect];
    
   }
-(void)SizeProduct:(UITableViewCell *)cell Meg:(NSArray *)arrInfo Index:(NSIndexPath *)indexPath{
    UILabel *labSize=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 90, 44)];
    UILabel *labStock=[[UILabel alloc]initWithFrame:CGRectMake(90, 0, 60, 44)];
    //            第一行
    if (indexPath.row==1) {
        
        UILabel *labCart=[[UILabel alloc]initWithFrame:CGRectMake(150, 9, 100, 44)];
        labSize.frame=CGRectMake(0, 9, 90, 44);
        labStock.frame=CGRectMake(90, 9, 60, 44);
        labSize.text=@"尺寸" ;
        labStock.text=@"库存";
        labCart.text=@"加入购物车";
        labCart.font=[UIFont systemFontOfSize:15];
        labCart.textAlignment=NSTextAlignmentCenter;
        [cell.contentView addSubview:labCart];
        UIImageView *imgLine=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 9)];
        imgLine.image=[UIImage imageNamed:@"sizeLine"];
        [cell.contentView addSubview:imgLine];

    }
    //            其他行
    else {
        UIButton *btnCart=[[UIButton alloc]initWithFrame:CGRectMake(165, 10, 70, 24)];
        [btnCart setTitle:@"加入" forState:UIControlStateNormal];
        [btnCart setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btnCart.titleLabel.font=[UIFont systemFontOfSize:14];
        btnCart.backgroundColor=ORANGE;
        [btnCart.layer setCornerRadius:12];
        [btnCart setClipsToBounds:YES];
        [cell.contentView addSubview:btnCart];
          NSDictionary *everySize=[arrInfo objectAtIndex:indexPath.row-2];
        labSize.text=[NSString stringWithFormat:@"%@",everySize[@"sizeName"]] ;
        labStock.text=@"...";
        if ([mlDicStock objectForKey:everySize[@"sku"]]) {
            labStock.text=[mlDicStock objectForKey:everySize[@"sku"]];
            
        }
        else{
            [self GetStock:everySize[@"sku"]];
        }
        
    }
    
    labSize.font=[UIFont systemFontOfSize:15];
    labSize.textAlignment=NSTextAlignmentCenter;
    [cell.contentView addSubview:labSize];
    labStock.font=[UIFont systemFontOfSize:15];
    labStock.textAlignment=NSTextAlignmentCenter;
    [cell.contentView addSubview:labStock];
    UIView *labLine=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight([self rectForRowAtIndexPath:indexPath])-1, CGRectGetWidth([self rectForRowAtIndexPath:indexPath]), 0.5)];
    labLine.backgroundColor=LINECOR;
    [cell.contentView addSubview:labLine];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (indexPath.section==0)return 100;
//    else if (indexPath.section==1) return 44;
//    else if (indexPath.section==2) return 90;
//    else return 100;
    
    if (indexPath.section==[self numberOfSections]-1) return 100;
    else{
        if (indexPath.row==0) return 90;
        else if(indexPath.row==1) return 54;
        else return 44;
    }
   

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==[self numberOfSections]-1||section==0) {
        return 36;
    }
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *vieResult=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, CGRectGetHeight([self rectForHeaderInSection:section]))];
    
    UILabel *result=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, vieResult.frame.size.height)];
    result.backgroundColor=[UIColor colorWithRed:229.0/255.0 green:229.0/255.0 blue:229.0/255.0 alpha:1];
    
    result.text=@"  当前搭配的单品尺码";
    [vieResult addSubview:result];
    UIButton *btnSelect;
       if (section==[self numberOfSections]-1) {
        result.text=@"  宝贝卖点";
           btnSelect=[[UIButton alloc]initWithFrame:CGRectMake(self.frame.size.width-40, 3, 30, 30)];
           result.font=[UIFont systemFontOfSize:15];
           [btnSelect setImage:[UIImage imageNamed:@"colorUp"] forState:UIControlStateNormal];
           [btnSelect addTarget:self action:@selector(HideRow:) forControlEvents:UIControlEventTouchUpInside];
           btnSelect.tag=10001+section;

    }
    [vieResult addSubview:btnSelect];
    return vieResult;
}
-(void)HideRow:(UIButton *)sender{
    [self beginUpdates];
    int section=sender.tag-10001;
    int startI=1;
    BOOL isOpen=NO;
    NSMutableArray* rowToInsert = [[NSMutableArray alloc] init];
    if (section==[self numberOfSections]-1) {
        startI=0;
    }
           for (int i=startI; i<[[self.mlRowNum objectAtIndex:section]intValue]; i++) {
            NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
            [rowToInsert addObject:indexPathToInsert];
        }
        if ([[self.mlIsShow objectAtIndex:section]boolValue]) {
            [self.mlIsShow setObject:[NSNumber numberWithBool:NO] atIndexedSubscript:section];
            [sender setImage:[UIImage imageNamed:@"colorUp"] forState:UIControlStateNormal];
            [self deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
        }
        else{
            
            [self.mlIsShow setObject:[NSNumber numberWithBool:YES] atIndexedSubscript:section];
            [sender setImage:[UIImage imageNamed:@"colorDown"] forState:UIControlStateNormal];
            [self insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationBottom];
            isOpen=YES;
            
        }
        [self endUpdates];
        if (isOpen) {
            [self scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:startI inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
   	
}


-(void)setItemId:(NSString *)itemId{
}
-(void)setItems:(NSDictionary *)items{
    NSArray *goods=items[@"goods"];
//    self.mlRowNum=[NSMutableArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:size.count],[NSNumber numberWithInt:arr.count-1],@"1" ,nil];
    self.mlRowNum=[NSMutableArray array];
     self.mlIsShow=[NSMutableArray array];
    for (int i=0; i<goods.count; i++) {
        NSArray *colors=[[goods objectAtIndex:i] objectForKey:@"colors"];
        NSArray *size=[[colors objectAtIndex:0] objectForKey:@"sizes"];
        [self.mlRowNum addObject:[NSNumber numberWithInt:size.count+2]];
        if (i==0)[self.mlIsShow  addObject:[NSNumber numberWithBool:YES]];
        else[self.mlIsShow  addObject:[NSNumber numberWithBool:NO]];
    }
    [self.mlRowNum addObject:[NSNumber numberWithInt:1]];
     [self.mlIsShow  addObject:[NSNumber numberWithBool:NO]];
    NSLog(@"%@",self.mlRowNum);
    _items=items;
    [self reloadData];
}

-(void)onItemClick:(id)sender{
//    UIView *view=sender;
//    int idx=view.tag;
//    NSString *itemId=[self.items objectAtIndex:idx];
//    self.itemId=itemId;
}

-(IBAction)onCloseClick:(id)sender{
    //    [self HideChild];
    //    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)onBuyClick:(id)sender{
    
////    NSString *skuId=[self getSkuId];
//    MainApp *app=[MainApp mainApp];
//    [app.shoppingList addObject:skuId];
//    [app requestProduct:skuId];
//    [[NSNotificationCenter defaultCenter] postNotificationName:ShoppingListNotification object:self];
//    
//    MBProgressHUD *hud=[[MBProgressHUD alloc] initWithView:self];
//    hud.mode=MBProgressHUDModeText;
//    hud.labelText=@"成功添加到购物车";
//    [self addSubview:hud];
//    [hud show:YES];
//    [hud hide:YES afterDelay:1.0];
}




@end
